import type { StorybookConfig } from "@storybook/react-webpack5";
import webpack from 'webpack';

const config: StorybookConfig = {
  // 配置故事文件的路径，确保匹配所有 .mdx, .js, .jsx, .ts, .tsx 文件
  stories: [
    // "../src/components/**/button.stories.tsx", // 添加具体的路径
    "../src/components/**/*.stories.@(ts|tsx)"
  ],

  addons: [
    "@storybook/preset-create-react-app",
    "@storybook/addon-onboarding",
    "@storybook/addon-essentials",
    "@chromatic-com/storybook",
    "@storybook/addon-interactions",
    "@storybook/addon-docs", // 添加 addon-docs
    '@storybook/react-docgen'
  ],

  framework: {
    name: "@storybook/react-webpack5",
    options: {},
  },

  staticDirs: ["../public"],

  webpackFinal: async (config: webpack.Configuration) => {
    // 确保 config.resolve 和 config.resolve.extensions 存在
    if (!config.resolve) {
      config.resolve = {};
    }

    if (!config.resolve.extensions) {
      config.resolve.extensions = [];
    }

    // 添加 .ts 和 .tsx 扩展名支持
    config.resolve.extensions.push('.ts', '.tsx');

    // 确保 config.module 存在，并且 module.rules 初始化为空数组
    if (!config.module) {
      config.module = { rules: [] };
    }

    // 确保 config.module.rules 存在并初始化为空数组
    if (!config.module.rules) {
      config.module.rules = [];
    }

    // 配置 svg 文件的处理
    config.module.rules.push({
      test: /\.tsx?$/,
      use: [
        {
          loader: require.resolve('babel-loader'),
          options: {
            presets: ['@babel/preset-react', '@babel/preset-typescript'],
          },
        },
        {
          loader: require.resolve('react-docgen-typescript-loader'),
        }
      ],
    });

    return config;
  },
};

export default config;
